import {connection} from './conn_to_sqlite.js'
import {generateId} from './ids.js'

const getJobTable = () => connection.table('job')

// count how many jobs
export async function countJobs() {
	const { count } = await getJobTable().first().count('* as count');
	return count;
}

// get all jobs
export async function getJobs(limit, offset) {
	const query = getJobTable().select().orderBy('createdAt', 'desc')
	if (limit) {
		query.limit(limit)
	}
	if (offset) {
		query.offset(offset)
	}
	return await query
} 

// get all jobs filter by companyId
export async function getJobsByCompany(companyId) {
	return await getJobTable().select().where({ companyId })
}

// get a job
export async function getJob(id) {
	return await getJobTable().first().where({ id })	
}

// insert a job
export async function createJob({ companyId, title, description }) {
	const job = {
		id: generateId(),
		companyId,
		title,
		description,
		createdAt: new Date().toISOString(), // format date	
	}
	await getJobTable().insert(job);
	console.log('[insert: ]', job)
	return job
}

// delete a job
export async function deleteJob(id, companyId) {
	const job = await getJobTable().first().where({ id, companyId });
	if (!job) {
		console.log("not found the provided job")
		return null;
	}
	await getJobTable().delete().where({ id })
	return job
}

// update a job
export async function updateJob({ id, companyId, title, description }) {
	const job = await getJobTable().first().where({ id, companyId })
	if (!job) {
		console.log("not found the provided job, nothing will update")
		return null
	}

	const toUpdateFields = { title, description }
	await getJobTable().update(toUpdateFields).where({ id })
	return {
		...job,
		...toUpdateFields,
	}
	
}
